//
//  BSJPhotoManager.m
//  ZYKBaiSiJie
//
//  Created by 张亚凯 on 16/5/9.
//  Copyright © 2016年 weilai. All rights reserved.
//

#import "BSJPhotoManager.h"
#import <Photos/Photos.h>

@implementation BSJPhotoManager

+ (PHAssetCollection *)getAssetCollection:(NSString*)title {
    
    //获取相册结构集
    PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    //遍历相册集
    for (PHAssetCollection *assetCollection in fetchResult) {
        //判断是否有跟传入的名称一样标题的相册
        if ([assetCollection.localizedTitle isEqualToString:title]) {
            //有的话返回相册
            return assetCollection;
        }
    }
    return nil;
}

+ (void)addImage:(UIImage *)image toAlbum:(NSString *)title completionHandler:(void(^)(BOOL success, NSError *error))completionHandler {
    //获取相簿
    PHPhotoLibrary *lib = [PHPhotoLibrary sharedPhotoLibrary];
    [lib performChanges:^{
        //只有在这个block中才可以操作相册
        PHAssetCollectionChangeRequest *assetCollectionChangeRequest;
        //获取相册
        PHAssetCollection *asset = [self getAssetCollection:title];
        
        if (asset) {
            //有自定义相册
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:asset];
        }else {
            //没有自定义相册就创建一个
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
            
        }
        //创建图片请求对象
        PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        
        //把图片放到自定义相册中  assetCollectionChangeRequest
        [assetCollectionChangeRequest addAssets:@[assetChangeRequest.placeholderForCreatedAsset]];
        
    } completionHandler:completionHandler];
    
}

@end
